package modele;

import java.awt.image.BufferedImage;
import java.io.ObjectInputStream.GetField;
import java.util.Random;

import memory.NombreImpairException;

public class MGrid {
	
	/*
	 * Modele d'une grille de jeu, caracterise :
	 * -L'ensemble des cartes de la partie
	 * -L'etat de la partie (gagnée ou en cours)
	 * -Leve une exception NombreImpairException à la construction si celle ci ne permet pas de donner un grille valide
	 * 
	 */
	
	protected int height, width;
	protected MCard[][] grille;
	protected boolean win, lock;
	
	public MGrid(int h, int l, int th) throws NombreImpairException {
		if((h*l)%2 != 0) throw new NombreImpairException();
		
		win = false;
		lock = false;
		height = h;
		width = l;
		
		
		grille = new MCard[height][width];
		MTheme theme = new MTheme(th);
		generateGame(theme);
		
	}

	public boolean isWin() {
		return win;
	}
	
	public MCard getCarte(int x, int y) {
		return grille[x][y];
	}
	
	public int getHeight() {
		return height;
	}
	
	public int getWidth() {
		return width;
	}
	
	protected void generateGame(MTheme th) {
		int[] coord;
		BufferedImage img;
		while(!isFull()) {
			img = th.getNewImage();
			coord = getEmptyCard();
			grille[coord[0]][coord[1]] = new MCard(img);
			coord = getEmptyCard();
			grille[coord[0]][coord[1]] = new MCard(img);
		}
	}
	
	protected int[] getEmptyCard() {
		Random gen = new Random();
		int i = gen.nextInt(getHeight());
		int j = gen.nextInt(getWidth());
		while(getCarte(i, j) != null) {
			i = gen.nextInt(getHeight());
			j = gen.nextInt(getWidth());
		}
		int[] res = {i, j};
		return res;
	}
	
	protected boolean isFull() {
		boolean isFull = true;
		int i=0, j=0;
		while(isFull && i<getHeight())
			while(isFull && j<getHeight())
				isFull = grille[i][j] != null;
		return isFull;
	}

}
